<template>
  <view class="payment-page">
    <!-- 页面头部 -->
    <u-navbar
      title="在线缴费"
      :left-icon-size="22"
      left-text="返回"
      @left-click="handleBack"
      :background="{ backgroundColor: '#007aff' }"
      :title-style="{ color: '#fff' }"
      :left-text-style="{ color: '#fff' }"
    />
    
    <!-- 费用信息卡片 -->
    <view class="fee-info-section" v-if="feeInfo">
      <view class="fee-card">
        <view class="fee-header">
          <text class="fee-title">{{ feeInfo.feeName }}</text>
          <u-tag :text="feeInfo.feeTypeName" type="primary" size="mini"></u-tag>
        </view>
        <view class="fee-details">
          <view class="detail-item">
            <text class="label">计费周期：</text>
            <text class="value">{{ feeInfo.billingPeriod }}</text>
          </view>
          <view class="detail-item">
            <text class="label">到期日期：</text>
            <text class="value due-date">{{ feeInfo.dueDate }}</text>
          </view>
          <view class="detail-item">
            <text class="label">房屋信息：</text>
            <text class="value">{{ feeInfo.householdInfo }}</text>
          </view>
        </view>
        <view class="fee-amount">
          <text class="amount-label">应缴金额</text>
          <text class="amount-value">¥{{ feeInfo.amount }}</text>
        </view>
      </view>
    </view>
    
    <!-- 支付方式选择 -->
    <view class="payment-method-section">
      <view class="section-title">
        <u-icon name="credit-card-fill" color="#007aff"></u-icon>
        <text>选择支付方式</text>
      </view>
      <view class="method-list">
        <view
          v-for="method in paymentMethods"
          :key="method.value"
          class="method-item"
          :class="{ active: selectedMethod === method.value }"
          @click="selectPaymentMethod(method.value)"
        >
          <view class="method-left">
            <u-icon :name="method.icon" :color="method.color" size="24"></u-icon>
            <text class="method-name">{{ method.label }}</text>
          </view>
          <view class="method-right">
            <u-icon
              name="checkmark-circle-fill"
              :color="selectedMethod === method.value ? '#007aff' : '#c8c9cc'"
              size="20"
            ></u-icon>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 优惠券选择 -->
    <view class="coupon-section">
      <view class="section-title">
        <u-icon name="ticket-fill" color="#ff9500"></u-icon>
        <text>优惠券</text>
      </view>
      <view class="coupon-selector" @click="showCouponModal = true">
        <text class="coupon-text">
          {{ selectedCoupon ? `已选择: ${selectedCoupon.name}` : '选择优惠券' }}
        </text>
        <u-icon name="arrow-right" color="#c8c9cc"></u-icon>
      </view>
    </view>
    
    <!-- 支付金额 -->
    <view class="amount-section">
      <view class="amount-row">
        <text class="amount-label">应付金额</text>
        <text class="amount-value">¥{{ feeInfo ? feeInfo.amount : '0.00' }}</text>
      </view>
      <view class="amount-row" v-if="selectedCoupon">
        <text class="amount-label">优惠券减免</text>
        <text class="amount-value discount">-¥{{ selectedCoupon.amount }}</text>
      </view>
      <view class="amount-row total">
        <text class="amount-label">实付金额</text>
        <text class="amount-value">¥{{ finalAmount }}</text>
      </view>
    </view>
    
    <!-- 支付按钮 -->
    <view class="payment-action">
      <u-button
        type="primary"
        :loading="paying"
        :disabled="!selectedMethod || !feeInfo"
        @click="handlePayment"
        text="立即支付"
        shape="circle"
        size="large"
      ></u-button>
    </view>
    
    <!-- 优惠券选择弹窗 -->
    <u-popup
      v-model="showCouponModal"
      mode="bottom"
      border-radius="20"
      :safe-area-inset-bottom="true"
    >
      <view class="coupon-modal">
        <view class="modal-header">
          <text class="modal-title">选择优惠券</text>
          <u-icon name="close" @click="showCouponModal = false"></u-icon>
        </view>
        <view class="coupon-list">
          <view
            v-for="coupon in availableCoupons"
            :key="coupon.id"
            class="coupon-item"
            :class="{ selected: selectedCoupon && selectedCoupon.id === coupon.id }"
            @click="selectCoupon(coupon)"
          >
            <view class="coupon-info">
              <text class="coupon-name">{{ coupon.name }}</text>
              <text class="coupon-desc">{{ coupon.description }}</text>
            </view>
            <view class="coupon-amount">¥{{ coupon.amount }}</view>
          </view>
          <view class="coupon-item" @click="selectCoupon(null)">
            <view class="coupon-info">
              <text class="coupon-name">不使用优惠券</text>
            </view>
          </view>
        </view>
      </view>
    </u-popup>
    
    <!-- 支付结果弹窗 -->
    <u-popup
      v-model="showResultModal"
      mode="center"
      :mask-close-able="false"
      border-radius="20"
    >
      <view class="result-modal">
        <view class="result-icon">
          <u-icon
            :name="paymentResult.success ? 'checkmark-circle-fill' : 'close-circle-fill'"
            :color="paymentResult.success ? '#52c41a' : '#ff4757'"
            size="40"
          ></u-icon>
        </view>
        <view class="result-title">
          {{ paymentResult.success ? '支付成功' : '支付失败' }}
        </view>
        <view class="result-message">
          {{ paymentResult.message }}
        </view>
        <view class="result-actions">
          <u-button
            v-if="paymentResult.success"
            type="primary"
            text="查看收据"
            @click="handleViewReceipt"
          ></u-button>
          <u-button
            v-if="!paymentResult.success"
            type="primary"
            text="重新支付"
            @click="handleRetryPayment"
          ></u-button>
          <u-button
            type="default"
            text="返回"
            @click="handleResultBack"
          ></u-button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { useUserStore } from '@/store'
import { propertyFeeApi, utilityFeeApi, paymentApi } from '@/api/property'

export default {
  name: 'Payment',
  setup() {
    const userStore = useUserStore()
    
    // 响应式数据
    const feeInfo = ref(null)
    const selectedMethod = ref('')
    const selectedCoupon = ref(null)
    const paying = ref(false)
    const showCouponModal = ref(false)
    const showResultModal = ref(false)
    const availableCoupons = ref([])
    const feeId = ref('')
    const feeType = ref('property') // 费用类型：property-物业费，utility-水电费
    
    const paymentResult = reactive({
      success: false,
      message: ''
    })
    
    // 支付方式列表
    const paymentMethods = [
      {
        label: '微信支付',
        value: 'wechat',
        icon: 'weixin-fill',
        color: '#09bb07'
      },
      {
        label: '支付宝',
        value: 'alipay', 
        icon: 'zhifubao-circle-fill',
        color: '#1677ff'
      },
      {
        label: '银行卡支付',
        value: 'bank',
        icon: 'credit-card-fill',
        color: '#ff6b6b'
      },
      {
        label: '余额支付',
        value: 'balance',
        icon: 'wallet-fill',
        color: '#ffa726'
      }
    ]
    
    // 计算属性
    const finalAmount = computed(() => {
      if (!feeInfo.value) return '0.00'
      let amount = parseFloat(feeInfo.value.amount)
      if (selectedCoupon.value) {
        amount = Math.max(0, amount - parseFloat(selectedCoupon.value.amount))
      }
      return amount.toFixed(2)
    })
    
    // 页面生命周期
    onLoad((options) => {
      if (options.feeId) {
        feeId.value = options.feeId
        feeType.value = options.feeType || 'property' // 默认为物业费
        loadFeeDetail(options.feeId)
        loadCouponList()
      }
    })
    
    // 方法
    const handleBack = () => {
      uni.navigateBack()
    }
    
    const selectPaymentMethod = (method) => {
      selectedMethod.value = method
    }
    
    const selectCoupon = (coupon) => {
      selectedCoupon.value = coupon
      showCouponModal.value = false
    }
    
    const loadFeeDetail = async (id) => {
      try {
        const response = await paymentApi.getFeeDetail(id)
        if (response.code === 200) {
          feeInfo.value = response.data
        }
      } catch (error) {
        console.error('加载费用详情失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      }
    }
    
    const loadCouponList = async () => {
      try {
        const response = await paymentApi.getCouponList({
          userId: userStore.userInfo.id,
          feeType: feeInfo.value?.feeType
        })
        if (response.code === 200) {
          availableCoupons.value = response.data
        }
      } catch (error) {
        console.error('加载优惠券失败:', error)
        availableCoupons.value = []
      }
    }
    
    const handlePayment = async () => {
      if (!selectedMethod.value || !feeInfo.value) {
        uni.showToast({
          title: '请选择支付方式',
          icon: 'none'
        })
        return
      }
      
      // 确认支付弹窗
      uni.showModal({
        title: '确认支付',
        content: `确认支付 ¥${finalAmount.value} 吗？`,
        success: async (res) => {
          if (res.confirm) {
            await processPayment()
          }
        }
      })
    }
    
    const processPayment = async () => {
      paying.value = true
      
      try {
        const paymentData = {
          feeId: feeId.value,
          userId: userStore.userInfo.id,
          amount: finalAmount.value,
          paymentMethod: selectedMethod.value,
          couponId: selectedCoupon.value?.id
        }
        
        const response = await paymentApi.createPayment(paymentData)
        
        if (response.code === 200) {
          // 调用相应的支付SDK
          await callPaymentSDK(response.data)
        } else {
          throw new Error(response.message)
        }
      } catch (error) {
        console.error('支付失败:', error)
        paymentResult.success = false
        paymentResult.message = error.message || '支付失败，请重试'
        showResultModal.value = true
      } finally {
        paying.value = false
      }
    }
    
    const callPaymentSDK = async (paymentInfo) => {
      try {
        let result
        
        switch (selectedMethod.value) {
          case 'wechat':
            result = await callWechatPay(paymentInfo)
            break
          case 'alipay':
            result = await callAlipay(paymentInfo)
            break
          case 'bank':
            result = await callBankPay(paymentInfo)
            break
          case 'balance':
            result = await callBalancePay(paymentInfo)
            break
          default:
            throw new Error('不支持的支付方式')
        }
        
        if (result.success) {
          paymentResult.success = true
          paymentResult.message = '支付成功！'
        } else {
          throw new Error(result.message)
        }
      } catch (error) {
        paymentResult.success = false
        paymentResult.message = error.message || '支付失败'
      }
      
      showResultModal.value = true
    }
    
    const callWechatPay = async (paymentInfo) => {
      // 模拟微信支付
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve({ success: true })
        }, 2000)
      })
    }
    
    const callAlipay = async (paymentInfo) => {
      // 模拟支付宝支付
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve({ success: true })
        }, 2000)
      })
    }
    
    const callBankPay = async (paymentInfo) => {
      // 模拟银行卡支付
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve({ success: true })
        }, 2000)
      })
    }
    
    const callBalancePay = async (paymentInfo) => {
      // 模拟余额支付
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve({ success: true })
        }, 2000)
      })
    }
    
    const handleViewReceipt = () => {
      showResultModal.value = false
      uni.navigateTo({
        url: `/pages/property/receipt?feeId=${feeId.value}`
      })
    }
    
    const handleRetryPayment = () => {
      showResultModal.value = false
      selectedMethod.value = ''
    }
    
    const handleResultBack = () => {
      showResultModal.value = false
      uni.navigateBack()
    }
    
    return {
      feeInfo,
      selectedMethod,
      selectedCoupon,
      paying,
      showCouponModal,
      showResultModal,
      availableCoupons,
      paymentResult,
      paymentMethods,
      finalAmount,
      handleBack,
      selectPaymentMethod,
      selectCoupon,
      handlePayment,
      handleViewReceipt,
      handleRetryPayment,
      handleResultBack
    }
  }
}
</script>

<style lang="scss" scoped>
.payment-page {
  min-height: 100vh;
  background-color: #f8f9fa;
}

.fee-info-section {
  padding: 20rpx;
  
  .fee-card {
    background: white;
    border-radius: 16rpx;
    padding: 30rpx;
    box-shadow: 0 2rpx 20rpx rgba(0,0,0,0.05);
    
    .fee-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 30rpx;
      
      .fee-title {
        font-size: 36rpx;
        font-weight: bold;
        color: #333;
      }
    }
    
    .fee-details {
      .detail-item {
        display: flex;
        justify-content: space-between;
        margin-bottom: 20rpx;
        
        .label {
          font-size: 28rpx;
          color: #666;
        }
        
        .value {
          font-size: 28rpx;
          color: #333;
          
          &.due-date {
            color: #ff4757;
          }
        }
      }
    }
    
    .fee-amount {
      text-align: center;
      padding: 30rpx 0;
      border-top: 1rpx solid #f0f0f0;
      margin-top: 30rpx;
      
      .amount-label {
        display: block;
        font-size: 28rpx;
        color: #666;
        margin-bottom: 10rpx;
      }
      
      .amount-value {
        font-size: 48rpx;
        font-weight: bold;
        color: #ff4757;
      }
    }
  }
}

.payment-method-section,
.coupon-section {
  background: white;
  margin: 20rpx;
  border-radius: 16rpx;
  padding: 30rpx;
  
  .section-title {
    display: flex;
    align-items: center;
    margin-bottom: 30rpx;
    
    text {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      margin-left: 10rpx;
    }
  }
}

.method-list {
  .method-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    &.active {
      background-color: #f0f8ff;
    }
    
    .method-left {
      display: flex;
      align-items: center;
      
      .method-name {
        font-size: 30rpx;
        color: #333;
        margin-left: 20rpx;
      }
    }
  }
}

.coupon-selector {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  background-color: #f8f9fa;
  border-radius: 12rpx;
  
  .coupon-text {
    font-size: 28rpx;
    color: #666;
  }
}

.amount-section {
  background: white;
  margin: 20rpx;
  border-radius: 16rpx;
  padding: 30rpx;
  
  .amount-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15rpx 0;
    
    &.total {
      border-top: 1rpx solid #f0f0f0;
      margin-top: 15rpx;
      padding-top: 30rpx;
      
      .amount-label,
      .amount-value {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }
    }
    
    .amount-label {
      font-size: 28rpx;
      color: #666;
    }
    
    .amount-value {
      font-size: 28rpx;
      color: #333;
      
      &.discount {
        color: #52c41a;
      }
    }
  }
}

.payment-action {
  padding: 30rpx 20rpx;
  padding-bottom: safe-area-inset-bottom;
}

.coupon-modal {
  padding: 40rpx;
  max-height: 60vh;
  
  .modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 40rpx;
    
    .modal-title {
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
    }
  }
  
  .coupon-list {
    .coupon-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 30rpx;
      margin-bottom: 20rpx;
      background-color: #f8f9fa;
      border-radius: 12rpx;
      
      &.selected {
        background-color: #e6f7ff;
        border: 1rpx solid #007aff;
      }
      
      .coupon-info {
        flex: 1;
        
        .coupon-name {
          display: block;
          font-size: 30rpx;
          color: #333;
          margin-bottom: 10rpx;
        }
        
        .coupon-desc {
          font-size: 24rpx;
          color: #666;
        }
      }
      
      .coupon-amount {
        font-size: 32rpx;
        font-weight: bold;
        color: #ff4757;
      }
    }
  }
}

.result-modal {
  padding: 60rpx 40rpx;
  text-align: center;
  
  .result-icon {
    margin-bottom: 30rpx;
  }
  
  .result-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }
  
  .result-message {
    font-size: 28rpx;
    color: #666;
    margin-bottom: 40rpx;
  }
  
  .result-actions {
    .u-button {
      margin-bottom: 20rpx;
    }
  }
}
</style> 